#include<iostream>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<vector>


#define N 10
int main()
{
    std::vector<pid_t>subids;
    int i=0;
    for(;i<N;i++)
    {
        pid_t id=fork();
        if(id==0)
        {
            int i=3;
            while(1)
            {
                printf("我是一个子进程，pid:%d, ppid:%d, count:%d\n",getpid(),getppid(),i);
                sleep(3);
                i--;
                break;
            }
            printf("子进程退出\n");
            int ret=1;
            if(ret==0)
            {
                exit(0);
            }
            else{
                exit(1);
            }
        }
        subids.push_back(id);
        
    }
    sleep(5);
    for(auto &sid : subids)
    {
        int status=0;
        printf("父进程等待子进程中.....\n");
        pid_t rid = waitpid(sid,&status,0);
        if(rid>0)
        {
            int exit_code=(status>>8)&0xFF;
            int exit_signal=status&0x7F;
            if(exit_code==0 && exit_signal==0)
            {
                printf("子进程运行完毕结果正确\n");
            }
            else if(exit_code>0 && exit_signal==0)
            {
                printf("子进程运行完毕，结果不正确：%d:%s\n",exit_code,strerror(exit_code));
            }
            else{
                printf("子进程出异常了,%d\n",exit_signal);
            }
        }
        else{
            printf("等待失败\n");
        }
    }
    sleep(2);
    return 0;
}
